/*
 * @Author: Damon Liu
 * @Date: 2025-04-16 15:35:01
 * @LastEditors: Damon Liu
 * @LastEditTime: 2025-04-17 15:35:30
 * @Description:  模拟一下请求
 */
import fetch from 'node-fetch';

// icon font 网站的cookie
const cookie = ``

// icon font 网站的token
const ctoken = ``

//  根据svgName获取svg
async function getSVGData(svgName){
  try {

    // 请求头
    const headers = {
      accept: 'application/json, text/javascript, */*; q=0.01',
      'accept-encoding': 'gzip, deflate, br, zstd',
      'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
      'bx-v': '2.5.28',
      'cache-control': 'no-cache',
      'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
      cookie: cookie,
      origin: 'https://www.iconfont.cn',
      pragma: 'no-cache',
      referer: `https://www.iconfont.cn/search/index?searchType=icon&q=${svgName}&page=1&fromCollection=-1`,
      'sec-ch-ua': '"Microsoft Edge";v="131", "Chromium";v="131", "Not_A Brand";v="24"',
      'sec-ch-ua-mobile': '?0',
      'sec-ch-ua-platform': '"Windows"',
      'sec-fetch-dest': 'empty',
      'sec-fetch-mode': 'cors',
      'sec-fetch-site': 'same-origin',
      'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0',
      'x-csrf-token': ctoken,
      'x-requested-with': 'XMLHttpRequest'
    };

    // 表单数据
    const formData = new URLSearchParams({
      q: `${svgName}`,
      sortType: 'updated_at',
      page: '1',
      pageSize: '54',
      sType: '',
      fromCollection: '-1',
      fills: '',
      t: `${(new Date()).getTime()}`,
      ctoken:  ctoken
    }).toString();

    // 发送请求
    const response = await fetch('https://www.iconfont.cn/api/icon/search.json', {
      method: 'POST',
      headers: headers,
      body: formData
    })
    const resJSON = await response.json() ;
    console.log(resJSON);
    if(resJSON?.code === 200) {
      return resJSON.icons?.[0]
    }
    else {
      throw new Error(`Failed to fetch svg data: ${response.statusText}`);
    }

  } catch (error) {
    console.error(error);
    return null;
  }
}

getSVGData('apple')